<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="提取计划名称：">
                            <el-input v-model="transferVal1" placeholder="请输入提取计划名称" />
                        </el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('safeProductionExtraction1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('safeProductionExtraction7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref='excelRef' :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="提取计划名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="planName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.planName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新时间" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新人" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="备注" align="center">
											<template #default="scope">
												<span v-if="scope.row.remark">{{ scope.row.remark }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="180" :show-overflow-tooltip="false" label="操作" align="center" fixed="right">
											<el-table-column align="center" fixed="right" min-width="180" :show-overflow-tooltip="false">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button v-if="$hasPer('safeProductionExtraction2:create')" @click="AddedDutyPersonnelInfo(scope.row)" class="icon-e" icon="ele-Plus" size="small" text type="primary"> 项目安全生产费用计划 </el-button>

														<el-button v-if="$hasPer('safeProductionExtraction3:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>

														<el-button v-if="$hasPer('safeProductionExtraction4:delete')" @click="deleteHandle(scope.row.n_Id)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="saveId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form label-width="110px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="planName" label="提取计划名称">
							<el-input v-model="ruleForm.planName" placeholder="提取计划名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注">
							<el-input type="textarea" v-model="ruleForm.remark" placeholder="备注" clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 安全生产费用项目提取 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showAddNodeDialogVisible" title="项目安全生产费用提取" width="50%" @close="cancelAddNodeClick">
			<el-divider content-position="left"> 基本信息 </el-divider>
			<el-form label-width="220px" ref="watchkeeperRuleFormRef" :model="watchkeeperRuleForm" :rules="watchkeeperRules">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item prop="projectName" label="项目名称">
							<el-input v-model="watchkeeperRuleForm.projectName" placeholder="项目名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item prop="extraction" label="本年度提取（万元）">
							<el-input v-model="watchkeeperRuleForm.extraction" placeholder="本年度提取（万元）" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item prop="operatingIncome" label="上一年度营业收入总额（万元）">
							<el-input v-model="watchkeeperRuleForm.operatingIncome" placeholder="上一年度营业收入总额（万元）" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"></el-col>
					<!-- 按钮 -->
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item>
							<el-button v-if="!editId" type="primary" @click="addDutyPerson(watchkeeperRuleFormRef)">新增</el-button>
							<el-button v-else type="primary" @click="addDutyPerson(watchkeeperRuleFormRef)">修改</el-button>
							<el-button @click="resetDutyPerson">重置</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-divider content-position="left"> 项目安全生产费用提取查看 </el-divider>
			<el-descriptions class="margin-top" :column="2" border min-width="120px" style="margin: 20px 0">
				<el-descriptions-item>
					<template #label> 提取计划名称</template>
					{{tableData.planName}}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label> 备注</template>
					{{tableData.remark}}
				</el-descriptions-item>
			</el-descriptions>
			<el-table :data="tableData.items" border style="width: 100%">
				<!-- <el-table-column min-width="90" :show-overflow-tooltip="true" align="center" prop="planName"
                    label="表格名称" /> -->
				<el-table-column min-width="60" :show-overflow-tooltip="true" align="center" type="index" label="序号" />
				<el-table-column min-width="90" :show-overflow-tooltip="true" align="center" prop="projectName" label="项目名称" />
				<el-table-column min-width="140" :show-overflow-tooltip="true" align="center" prop="operatingIncome" label="上一年度营业收入总额（万元）"> </el-table-column>
				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" prop="extraction" label="本年度提取（万元）"> </el-table-column>
				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" prop="annualWithdrawalRatio" label="年度提取比例"> </el-table-column>
				<el-table-column min-width="140" :show-overflow-tooltip="true" align="center" prop="annualMonthlyWithdrawals" label="本年度每月平均提取金额（万元）"> </el-table-column>
				<el-table-column min-width="120" :show-overflow-tooltip="true" align="center" label="操作">
					<template #default="{ row }">
						<el-button text type="primary" @click="editClick(row)">编辑</el-button>
						<el-button text type="danger" @click="deleteClick(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import SearchModel from '/@/views/sms/component/search-model.vue';
import {
	getSafetyCostApi,
	deleteSafetyCostApi,
	editSafetyCostApi,
	addSafetyCostApi,
	addSafetyCostItemApi,
	getSafetyCostItemApi,
	deleteSafetyCostItemApi,
	editSafetyCostItemApi,
	getSafetyPlanDetailApiV2,
} from '/@/api/sms/HazardousChemicalsInterface';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { exportToExcel } from '/@/utils/exportToExcel';
/***** 查询 *****/
let searchObj: any = reactive({});
const transferVal1 = ref();
const searchClick = () => {
	// searchObj.PlanName = transferVal1.value;
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};
const resetClick = () => {
	// transferVal1.value = '';
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};

/***** 安全生产费用提取计划curd *****/
//新增
const showDialogVisible = ref(false);
const ruleForm = reactive({
	planName: '', //提取计划名称
	remark: '', //备注
});
const addNodeClick = async () => {
	showDialogVisible.value = true;
};

// 编辑
const saveId = ref(0);
const nodeClick = async (row: any) => {
	if (row.n_Id) {
		saveId.value = row.n_Id;
		ruleForm.planName = row.planName;
		ruleForm.remark = row.remark; //备注
	}
	showDialogVisible.value = true;
};

//删除
const deleteHandle = async (val: String | Number) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { n_Id: val };
			try {
				let res: any = await deleteSafetyCostApi(param);
				if (res.success) {
					getData();
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

/***** 新增编辑表单校验和事件 *****/
const ruleFormRef = ref();
const rules = reactive({
	planName: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});
//取消
const cancelUseClick = () => {
	showDialogVisible.value = false;
	saveId.value = 0;
	ruleForm.planName = '';
	ruleForm.remark = ''; //备注

	ruleFormRef.value!.clearValidate();
};
//提交
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (saveId.value) {
				editSafetyCostApi({ ...ruleForm, n_Id: saveId.value });
			} else {
				addSafetyCostApi(ruleForm);
			}
			setTimeout(() => {
				cancelUseClick();
				getData();
			}, 100);
		} else {
			console.log('error submit!', fields);
		}
	});
};

/***** 安全生产费用提取项目crud *****/

// 表单校验
const watchkeeperRuleFormRef = ref();
const watchkeeperRules = reactive({
	projectName: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	operatingIncome: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^[1-9]\d*$/, message: '请输入数字', trigger: 'blur' },
	],
	extraction: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^[1-9]\d*$/, message: '请输入数字', trigger: 'blur' },
	],
});
const watchkeeperRuleForm: any = reactive({
	projectName: '',
	planId: 0,
	operatingIncome: 0,
	extraction: 0,
});
//curd弹窗
const AddedDutyPersonnelInfo = async (row: any) => {
	watchkeeperRuleForm.planId = row.n_Id;
	const res = await getSafetyPlanDetailApiV2({ PlanId: row.n_Id });
	tableData.value = res.data;
	showAddNodeDialogVisible.value = true;
};
//新增
const addDutyPerson = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (editId.value) {
				console.log(editId.value);
				editSafetyCostItemApi({ ...watchkeeperRuleForm, id: editId.value }).then(() => {
					getSafetyPlanDetailApiV2({ PlanId: watchkeeperRuleForm.planId }).then((res) => {
						tableData.value = res.data;
						resetDutyPerson();
					});
				});
			} else {
				addSafetyCostItemApi(watchkeeperRuleForm).then(() => {
					getSafetyPlanDetailApiV2({ PlanId: watchkeeperRuleForm.planId }).then((res) => {
						tableData.value = res.data;
						resetDutyPerson();
					});
				});
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};

// 编辑
const editId = ref(0);
const editClick = async (row: any) => {
	editId.value = row.n_Id;
	watchkeeperRuleForm.projectName = row.projectName;
	watchkeeperRuleForm.operatingIncome = row.operatingIncome;
	watchkeeperRuleForm.extraction = row.extraction;
};

// 删除
const deleteClick = async (row: any) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: row.n_Id };
			try {
				let res: any = await deleteSafetyCostItemApi(param);
				if (res.success) {
					const res = await getSafetyPlanDetailApiV2({ PlanId: watchkeeperRuleForm.planId });
					tableData.value = res.data;
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

// 重置信息
const resetDutyPerson = () => {
	editId.value = 0;
	watchkeeperRuleForm.projectName = '';
	watchkeeperRuleForm.operatingIncome = 0;
	watchkeeperRuleForm.extraction = 0;
};
//表单取消事件
const showAddNodeDialogVisible = ref(false);
const tableData: any = ref();
const cancelAddNodeClick = () => {
	showAddNodeDialogVisible.value = false;
	watchkeeperRuleFormRef.value?.clearValidate();
	tableData.value = null;
	editId.value = 0;
	watchkeeperRuleForm.planId = '';
};

/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'planName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'PlanName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '提取计划名称', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};

const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};


  /*** ================================= 导出数据函数操作 ================================= */
  const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef.value){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['提取计划名称'] = item.planName ? item.planName : '-';

                        tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
                        tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
                        tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
                        tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'安全生产费用提取.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getSafetyCostApi, {}, searchObj);

onMounted(() => {
	initInfoFun();
});
</script>

<style lang="scss">
@import '../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
